﻿using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Server
{
    class Program
    {
        static byte[] _bufferRec;
        static EndPoint _ep;
        static void Main(string[] args)
        {
            //string ip = Console.ReadLine();
            //1) Creo Endpoint local
            // ReSharper disable InconsistentNaming
            IPEndPoint locEP = new IPEndPoint(IPAddress.Any, 12890);
            // ReSharper restore InconsistentNaming
            //2) Creo Socket/
            Socket udpSocket = new Socket(AddressFamily.InterNetwork, 
            SocketType.Dgram, ProtocolType.Udp);
            udpSocket.Bind(locEP);
            //3) Asocio con una dir de multi cast           
            udpSocket.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.1.1.1")));
            udpSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
            _ep = new IPEndPoint(IPAddress.Any, 12890);

            _bufferRec = new byte[50];
            udpSocket.BeginReceiveFrom(_bufferRec,0,50,SocketFlags.None,ref _ep, ReceiveComplete, udpSocket);
            //udpSocket.BeginReceive(bufferRec, 0, 10, SocketFlags.None, new AsyncCallback(ReceiveComplete), udpSocket);
            Console.ReadLine();
        }

        static void ReceiveComplete(IAsyncResult result)
        {
            try
            {

                Socket socket = result.AsyncState as Socket;
                if (socket != null)
                {
                    int bytesReceived = socket.EndReceiveFrom(result, ref _ep);
                    UTF8Encoding enc = new UTF8Encoding();
                    Console.WriteLine(enc.GetString(_bufferRec, 0, bytesReceived));
                    IPEndPoint emp = (IPEndPoint) socket.LocalEndPoint;
                    Console.WriteLine(emp.Address);
                    Console.WriteLine(_ep.ToString());

                    //byte[] buffer = enc.GetBytes("hola2");

                    //socket.SendTo(buffer, SocketFlags.None, _ep);
                }
                if (socket != null)
                    socket.BeginReceiveFrom(_bufferRec, 0, 50, SocketFlags.None, ref _ep, ReceiveComplete, socket);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}
